const User = require('../../models/user')
const jwt = require('../../jwt')

module.exports = (req, res) => {
  const formData = {}
  // console.log(req.body);
  formData.username = req.body.username
  formData.password = req.body.password

  User.findOne({
    username: formData.username,
    password: formData.password
  }, (err, userDoc) => {
    if (err) {
      return res.status(500).json({
        err_code: 500,
        message: err.message
      })
    }
    // 若没有此项数据
    if (!userDoc) {
      return res.status(200).json({
        err_code: 1,
        message: '账号不存在'
      })
    }
    userDoc.login_time = new Date
    userDoc.last_modified_time = new Date
    User.findByIdAndUpdate({ _id: userDoc._id }, userDoc, (err) => {
      // 验证成功,生成token,发送给客户端
      const token = jwt.generateToken(userDoc.username, userDoc._id)
      // req.session.userInfo = userDoc;
      res.status(200).json({
        err_code: 0,
        token,
        data: userDoc,
        message: '登录成功'
      })
    })



    console.log(userDoc);
  })
}